/**
 * 
 */
package com.demo2do.strawberry.handler.impl;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Component;

import com.demo2do.strawberry.handler.FileHandler;

/**
 * @author Downpour
 */
@Component("fileHandler")
public class FileHandlerImpl implements FileHandler {
	
	private Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
	
	@Value("#{config['startup.temp.folder']}")
	private String localTempPath; 

	@Value("#{config['startup.upload.folder']}")
	private String localPicturePath;

	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.handler.FileHandler#save(java.lang.String, java.io.InputStream, boolean)
	 */
	public String save(String fileName, InputStream inputStream, boolean isDirect) {
		
		String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
		String encodingFileName = passwordEncoder.encodePassword(fileName, new Date()) + "." + extension;
		
		try {
			
			File file = null;
			if(isDirect) {
				 file = new File(this.localPicturePath + encodingFileName);
			} else {
				file = new File(this.localTempPath + encodingFileName);
			}
			
			FileUtils.copyInputStreamToFile(inputStream, file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encodingFileName;
		
	}
	
	/* (non-Javadoc)
	 * @see com.demo2do.darth.service.FileHandler#transfer(java.lang.String)
	 */
	public void transfer(String fileName) {
		try {
			File src = new File(this.localTempPath + fileName);
			File dest = new File(this.localPicturePath);
			FileUtils.copyFileToDirectory(src, dest);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/* (non-Javadoc)
	 * @see com.demo2do.apple.handler.FileHandler#delete(java.lang.String)
	 */
	public void delete(String fileName) {
		
		File file = new File(this.localPicturePath + fileName);
		FileUtils.deleteQuietly(file);
	}

}
